-- UISkyCityPetList
-- Create by chendh
-- 天空之城冈布奥列表

-- UISkyCityPetList继承自Layer
UISkyCityPetList = class("UISkyCityPetList", function()
    return cc.Layer:create();
end);

function UISkyCityPetList.create(campId, classId, groupIndex)
    return UISkyCityPetList.new(campId, classId, groupIndex);
end

-- 最大行数
local MAX_GRID_ROW  = 4;
local PAGE_COLUMN   = 4;
local ITEM_NAME     = "item";

local MAX_PAGE_NUM  = 3;
local petList       = {};
local robotList     = {};

-- 内部函数声明

-- 构造函数
function UISkyCityPetList:ctor(campId, classId, groupIndex)
    -- 初始化
    self:setName("UISkyCityPetList");
    local node = cc.CSLoader:createNode("layout/sky_city/SkyCityTeam.csb");
    self:addChild(node);
    self.node = node;
    self.classId = classId;
    self.campId = campId;
    self.groupIndex = groupIndex;
    self.selectIndex = 1;

    local CT = node:getChildByName("CT");
    local template = CT:getChildByName("template");
    local scrollview = template:getChildByName("scroll_view");
    self.CT = CT;
    self.scrollView = scrollview;
    self.scrollView:setVisible(true);

    -- 垂直滑动，需要显示上下蒙版
    local mask1 = findChildByName(self.node, "CT/template/mask1");
    mask1:setVisible(true);
    local mask2 = findChildByName(self.node, "CT/template/mask2");
    mask2:setVisible(true);

        -- 调整下标题背景图片资源
    local bgTypeImg1 = findChildByName(self.node, "CT/template/bg_type");
    local bgTypeImg2 = findChildByName(self.node, "CT/template/bg_type2");
    bgTypeImg2:setVisible(true);
    bgTypeImg1:loadTexture(getTitleBgIconPath("airship"));
    bgTypeImg2:loadTexture(getTitleBgIconPath("airship"));
    -- 修改滚动方向
    -- 1 垂直
    -- 2 水平
    self.scrollView:setDirection(1);

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 初始化列表数据
    self:initData();

    -- 初始化格子
    self:initGrids(self.node);

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UISkyCityPetList:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 初始化飞船列表数据
function UISkyCityPetList:initData()
    petList       = {};
    robotList     = {};

    -- 收集冈布奥列表
    local group = SkyCombatM.getGroup(self.campId);
    local allPetList = ME.user:getAllPetIds();

    for _, id in ipairs(allPetList) do
        if table.indexOf(group, id) <= 0 and CampM.getPetCamp(id) == self.campId then
            table.insert(petList, id);
        end
    end

    -- 排序
    self:sortData(petList);

    -- 收集机器人列表
    robotList = SkyRobotM.fetchRobotList();

    local function sortRobot(id1, id2)
        return SkyRobotM.query(id1, "fight_ability") > SkyRobotM.query(id2, "fight_ability");
    end

    if #robotList > 0 then
        table.sort(robotList, sortRobot);
    end
end

-- 初始化格子
function UISkyCityPetList:initGrids(node)
    local w = DESIGN_WIDTH;
    local h = DESIGN_HEIGHT;

    -- 图标间距(横向)
    local wGap = 1;

    -- 图标间距(纵向)
    local hGap = 10;

    -- 图标宽度
    local iconWidth = 127;

    -- 图片高度
    local iconHeight = 110;

    local topHGap  = 15;
    local bottomHGap  = 50;
    local leftWGap = 10;

    -- 总数
    local totalCount = #petList + #robotList;

    self.scrollView.rows = {};
    self.scrollView:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/sky_city/SkyCityPetItem.csb");
    -- @param windowNode    界面节点
    -- @param scrollNode    容器节点
    -- @param itemNode      单元格的节点
    -- @param totalNum      单元格总数
    -- @param maxRowNum     最大行数
    -- @param pageColNum    单页可以显示下的列数
    -- @param wGap          单元格间距(横向) 这里作为最小值使用
    -- @param hGap          单元格间距(纵向)
    -- @param iconWidth     单元格宽度
    -- @param iconHeight    单元格高度
    -- @param topHGap       上方留
    -- @param leftWGap      左右留白  这里作为最小值使用
    -- @param touchEvent    点击事件注册函数
    initScrollGridsVertical(self, self.scrollView, itemNode, totalCount, MAX_GRID_ROW, PAGE_COLUMN, wGap, hGap, iconWidth, iconHeight, topHGap, bottomHGap, leftWGap, self.registerPetItemTouchEvent);

    for _, child in ipairs(self.scrollView.rows) do
        child:setScale(0.88);
    end
end

-- 排序
function UISkyCityPetList:sortData(list)
    local function sortPet(id1, id2)
        local pet1 =  ME.user.pets[id1];
        local pet2 =  ME.user.pets[id2];
        local petAbility1 = FormulaM.invoke("CALC_SINGLE_PET_ABILITY", pet1);
        local petAbility2 = FormulaM.invoke("CALC_SINGLE_PET_ABILITY", pet2);

        if petAbility1 == petAbility2 then
            local list1 = SkyShipSkillM.getShipSkillsByPetId(id1);
            local list2 = SkyShipSkillM.getShipSkillsByPetId(id2);

            if #list1 == #list2 then
                return id1 > id2;
            else
                return #list1 > #list2;
            end
        else
            return petAbility1 > petAbility2;
        end
    end

    if #list > 0 then
        table.sort(list, sortPet);
    end
end

-- 显示英雄选择界面
function UISkyCityPetList:redraw()
    -- 显示标题
    local titleLabel = findChildByName(self.node, "CT/template/title");
    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(getLocStr("sky_city_group_select"));
    local petNameLabel = findChildByName(self.node, "CT/pet_name");
    petNameLabel:setVisible(false);

    if not petList then
        cclog("收集编组信息失败。");
        return;
    end

    local totalGridCount = #petList + #robotList;
    -- 显示信息
    for i = 1, totalGridCount do
        local grid = self.scrollView:getChildByName("item" .. i);
        if grid then
            --  初始化格子信息
            self:initGridInfo(grid);
        end
    end
end

--  初始化格子信息
function UISkyCityPetList:initGridInfo(grid)
    local bgImg = grid:getChildByName("bg");
    local grayBgImg = grid:getChildByName("gray_bg");
    local focusImg = grid:getChildByName("focus");
    local iconImg = grid:getChildByName("icon");
    local descLable = grid:getChildByName("desc");
    local skillNode = grid:getChildByName("skill");
    local numLabel = grid:getChildByName("num");

    grayBgImg:setVisible(false);
    descLable:setVisible(true);
    focusImg:setVisible(false);
    numLabel:setVisible(false);
    bgImg:setVisible(true);
    iconImg:setVisible(true);

    if grid.index <= #petList then
        -- 冈布奥
        -- 冈布奥使用普通的框
        bgImg:loadTexture(getFrameBgIconPath("normal"));

        local petId = petList[grid.index];
		local pet = PetM.getMyPet(petId);
        local iconIndex = pet:getIcon();
        iconImg:loadTexture(getHeroIconPath(iconIndex));

        local pet =  ME.user.pets[petId];
        local petAbility = FormulaM.invoke("CALC_SINGLE_PET_ABILITY", pet)
        TextStyleM.setTextStyle(descLable, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -3);
        descLable:setString(petAbility);

        -- 绘制冈布奥当前的秘宝信息
        local petSkillList = SkyShipSkillM.getShipSkillsByPetId(petId);

        skillNode:removeAllChildren();
        local lightStarPath = "images/ui/symbol/point_01.png";
        local darkStarPath = "images/ui/symbol/point_02.png";
        local sinkerLayer = createStarLayerEx(0, #petSkillList, lightStarPath, darkStarPath, "right", -0.25);
        sinkerLayer:setScale(1.2 * sinkerLayer:getScale());
        sinkerLayer:setScaleX(-1 * sinkerLayer:getScaleX());
        skillNode:addChild(sinkerLayer);
        skillNode:setVisible(true);
    else
        -- 机器人
        -- 机器人使用和秘宝一样的框
        bgImg:loadTexture(getFrameBgIconPath("airship_skill"));

        local robatId = robotList[grid.index - #petList];
        -- 机器人图标
        local iconIndex = SkyRobotM.query(robatId, "icon");
        iconImg:loadTexture(getRobotIconPath(iconIndex));

        -- 机器人的数量
        local robotInfo = SkyRobotM.getRobotInfo(robatId);

        local num = robotInfo["total"] - robotInfo["fighting"];
        if num > 1 then
            numLabel:setVisible(true);
            TextStyleM.setTextStyle(numLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -3);
            numLabel:setString(num);
        end

        -- 机器人的战力
        descLable:setVisible(true);
        TextStyleM.setTextStyle(descLable, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_LIGHT_BLUE, true, -3);
        descLable:setString(SkyRobotM.query(robatId, "fight_ability"));

        skillNode:setVisible(false);
    end
end

-- 注册飞艇点击事件
function UISkyCityPetList:registerPetItemTouchEvent(node)
    -- 注册商品图标点击事件
    local bgImg = node:getChildByName("bg");
    local function onClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 打开详细信息界面
            require "game/ui/form/sky_city/UISkyCityPetInfo"

            local petId;
            local targetType;
            if node.index <= #petList then
                targetType = "pet";
                petId = petList[node.index];
            else
                targetType = "robot";
                petId = robotList[node.index - #petList];
            end

            -- 打开冈布奥详细信息界面
            local uiForm = UISkyCityPetInfo.create(petId, self.campId, targetType, self.groupIndex, "actived");
            UIMgr.getCurrentScene():addForm(uiForm);
            AudioM.playFx("ui_open1");
        end
    end
    bgImg:addTouchEventListener(onClick);
end

-- 注册事件处理回调函数
function UISkyCityPetList:registerEventCallback()
    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            EventMgr.removeAll("UISkyCityPetList");
        elseif eventType == "enter" then

        end
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UISkyCityPetList", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UISkyCityPetList" then
            local btNode = findChildByName(self.node, "BT");
            btNode:setVisible(true);

            self:setVisible(true);
        elseif para["lose"] == "UISkyCityPetList" then
            local btNode = findChildByName(self.node, "BT");
            btNode:setVisible(false);
        end
    end);

end

-- 注册点击事件
function UISkyCityPetList:registerTouchEvent()
    -- 注册确定按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onOkClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("ship_return");
            UIMgr.getCurrentScene():removeFormByName("UISkyCityPetList");
        end
    end
    AddBackEventHandler(self, btnBack, onOkClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    local btnInfo = findChildByName(self.node, "BT/btn_info");
    btnInfo:setVisible(false);

    local btnActived = findChildByName(self.node, "BT/btn_actived");
    btnActived:setVisible(false);
end


